package com.ncmem.up6.biz;

import com.ncmem.up6.model.DnFileInf;
import com.ncmem.up6.sql.*;
import com.ncmem.up6.utils.ConfigReader;
import com.ncmem.up6.utils.DataBaseType;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;

/**
 * 构建文件夹下载数据
 * 格式：
 * [
 *   {f_id,nameLoc,pathSvr,pathRel,lenSvr,sizeSvr}
 *   {f_id,nameLoc,pathSvr,pathRel,lenSvr,sizeSvr}
 * ]
 * @author zysoft
 *
 */
public class FolderBuilder {
	
	/**
	 * 
	 * @param id 文件夹ID
	 * @return
	 */
    public List<DnFileInf> build(String id) throws SQLException, InstantiationException, ParseException, IllegalAccessException {
        DnFileInf dir = SqlTable.build("up6_files").readOne(DnFileInf.build(),
                SqlWhere.build().eq("f_id",id));
        //子目录
        if(dir==null)
        {
            dir = SqlTable.build("up6_folders").readOne(DnFileInf.build(),
                    SqlWhere.build().eq("f_id",id));
        }
        int index = dir.pathRel.length();
        String pathRoot = dir.pathRel;

        String cdtPathRel = String.format("CHARINDEX('%s',f_pathRel)=1",pathRoot+"/");
        if(ConfigReader.dbType() == DataBaseType.MySQL)
            cdtPathRel = String.format("locate('%s',f_pathRel)=1",pathRoot+"/");
        else if(ConfigReader.dbType() == DataBaseType.Oracle)
            cdtPathRel = String.format("instr(f_pathRel,'%s')=1",pathRoot+"/");

        //查询文件
        SqlWhere w = SqlWhere.build();
        w.sql("f_pathRel",cdtPathRel)
                .eq("f_fdTask",false)
                .eq("f_deleted",false);

        List<DnFileInf> files = SqlTable.build("up6_files").reads(DnFileInf.build(),w);
        for(DnFileInf f : files)
        {
            f.f_id = f.id;
            f.pathRel = f.pathRel.substring(index);
            f.lenSvrSec = f.lenLocSec;
            f.fields.put("object_key",f.object_key);
        }

        return files;
    }
}
